package com.group01.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group01.community.entity.SysUser;
import com.group01.community.entity.SysUserPost;
import com.group01.community.entity.SysUserRole;
import com.group01.community.entity.vo.SysUserInfoVo;
import com.group01.community.entity.vo.SysUserVo;
import com.group01.community.mapper.SysUserMapper;
import com.group01.community.mapper.SysUserPostMapper;
import com.group01.community.mapper.SysUserRoleMapper;
import com.group01.community.service.SysUserService;
import com.group01.community.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUserPostMapper sysUserPostMapper;

    @Override
    public void insertBatch(List<SysUser> sysUsers) {
        for (SysUser sysUser : sysUsers) {
            if (!ExcelUtils.isAllFieldNull(sysUser)) {
                sysUserMapper.insertBatch(sysUser);
            }
        }
    }

    @Override
    public SysUser selectRoleByUserId(Long userId) {
        return sysUserMapper.selectRoleByUserId(userId);
    }

    @Override
    public SysUserVo getUserRoleByUsername(String username) {
        return sysUserMapper.selectUserRoleByUsername(username);
    }

    @Override
    public SysUserInfoVo getUserInfoByUserName(String username) {
        return sysUserMapper.getUserInfoByUserName(username);
    }

    @Override
    public void updateUserInfo(SysUser sysUser) {
        sysUserMapper.updateUserInfo(sysUser);
    }

    @Override
    public List<SysUser> getDeptUserByDeptId(Long deptId) {
        return sysUserMapper.getDeptUserByDeptId(deptId);
    }

    @Override
    public IPage<SysUserInfoVo> selectUserPage(Long current, Long size, SysUser user) {
        IPage<SysUserInfoVo> sysUserInfoVoIPage = sysUserMapper.selectUserPage(new Page<>(current, size), user);
        if (sysUserInfoVoIPage != null && sysUserInfoVoIPage.getRecords() != null && sysUserInfoVoIPage.getRecords().size() > 0){
            for (SysUserInfoVo record : sysUserInfoVoIPage.getRecords()) {
                //查岗位信息
                QueryWrapper<SysUserPost> queryWrapperPost = new QueryWrapper<>();
                queryWrapperPost.eq("user_id", record.getUserId());
                List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(queryWrapperPost);
                if (sysUserPosts != null && sysUserPosts.size() > 0){
                    record.setPost(sysUserPosts.get(0).getPostId());
                }

                // 查角色信息
                QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", record.getUserId());
                List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);

                if (sysUserRoles == null || sysUserRoles.isEmpty()){
                    continue;
                }

                List<String> roleIds = new ArrayList<>();
                for (Long roleId : sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList())) {
                    roleIds.add(String.valueOf(roleId));
                }
                record.setRoleIds(roleIds);
            }
        }

        return sysUserInfoVoIPage;
    }

    @Override
    public void updatePassword(String password) {
        sysUserMapper.updatePassword(password);
    }

    @Override
    public void updateUserRole(SysUser sysUser, String flag) {
        if (sysUser.getUserId() == null){
            throw new RuntimeException("用户id为空");
        }

        List<String> roleIds = sysUser.getRoleIds();

        if (roleIds != null && roleIds.size() > 0){
            sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getUserId()));
            for (String roleId : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setRoleId(Long.valueOf(roleId));
                sysUserRoleMapper.insert(sysUserRole);
            }
        }

        if ("update".equals(flag) && (roleIds == null || roleIds.isEmpty())){
            sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getUserId()));
        }
    }
}
